import { Injector } from '@angular/core';
import { ControlService } from '../../../../service/control.service';
import { DgControl } from '../../../../utils/dg-control';
import { DomService, RefreshFormService, FormBasicService, WebCmdService } from '@farris/designer-services';
import { IdService } from '@farris/ui-common';

export class QuerySchemeBuilderService {

    private domService: DomService;
    public refreshFormService: RefreshFormService;
    private controlService: ControlService;
    private formBasicService: FormBasicService;
    private webCmdService: WebCmdService;



    // 筛选方案相关配置
    querySchemeConfig: any;

    /** 加载命令的控制器id */
    loadCommandCmpId = '54bddc89-5f7e-4b91-9c45-80dd6606cfe9';

    constructor(private injector: Injector) {

        this.domService = this.injector.get(DomService);
        this.refreshFormService = this.injector.get(RefreshFormService);
        this.controlService = this.injector.get(ControlService);
        this.formBasicService = this.injector.get(FormBasicService);
        this.webCmdService = this.injector.get(WebCmdService);

        const templateOutlineSchema = this.domService.templateOutlineSchema || [];
        const schemeConfig = templateOutlineSchema.find(schema => schema.queryScheme && schema.queryScheme.canEnable);
        if (schemeConfig) {
            this.querySchemeConfig = schemeConfig.queryScheme;
        }
    }

    /**
     * 创建筛选方案控件
     * @param fieldConfigs 方案选定的字段
     * @param controlDraggable 容器是否可拖拽
     */
    createQuerySchemeInDocument(fieldConfigs: any[], presetFieldConfigs = []) {
        if (!this.querySchemeConfig) {
            return;
        }
        // 1、组装筛选方案容器和筛选方案dom结构
        const querySchemeContainer = this.controlService.getControlMetaData(DgControl.Section.type);
        const querySchemeMetadata = this.controlService.getControlMetaData(DgControl.QueryScheme.type);

        const gridPrefix = Math.random().toString(36).slice(2, 6);
        Object.assign(querySchemeContainer, {
            id: 'query-scheme-container-' + gridPrefix,
            appearance: {
                class: 'f-section-scheme f-section-in-managelist'
            },
            showHeader: false,
            mainTitle: '',
            enableAccordion: false,
            enableMaximize: false,
            contents: [querySchemeMetadata]

        });

        Object.assign(querySchemeMetadata, {
            id: 'query-scheme-' + gridPrefix,
            fieldConfigs,
            presetFieldConfigs,
            formId: this.formBasicService.formMetaBasicInfo.code
        });

        // 2、在指定位置插入筛选(默认为根组件)
        const rootComponentJson = this.domService.getComponentById('root-component');
        const listFilterContainerParent = this.domService.getNodeByIdPath(rootComponentJson, this.querySchemeConfig.position);
        listFilterContainerParent.contents.unshift(querySchemeContainer);


        // 3、关联DOM处理--目前只处理新增样式
        if (this.querySchemeConfig.relatedClass && this.querySchemeConfig.relatedClass.length) {
            this.querySchemeConfig.relatedClass.forEach(r => {
                const relateDom = this.domService.getNodeByIdPath(rootComponentJson, r.path);
                if (relateDom) {
                    if (!relateDom.appearance) {
                        relateDom.appearance.class = r.class;
                    } else {
                        relateDom.appearance.class = relateDom.appearance.class + ' ' + r.class;
                    }
                }

            });
        }
        // 4、预置筛选方案相关的变量
        const viewModel = this.domService.getViewModelById(rootComponentJson.viewModel);
        if (viewModel && viewModel.states) {
            if (!viewModel.states.find(state => state.code === 'originalFilterConditionList')) {
                viewModel.states.push(
                    {
                        id: new IdService().generate(),
                        category: 'locale',
                        code: 'originalFilterConditionList',
                        name: '筛选方案筛选条件',
                        type: 'String'
                    }
                );
            }
        }
        // 5、预制筛选方案查询命令
        let newFilterCommandId;
        if (viewModel && viewModel.commands) {
            let filterCommand = viewModel.commands.find(command => command.handlerName === 'Filter' && command.cmpId === this.loadCommandCmpId);
            if (!filterCommand) {
                newFilterCommandId = new IdService().generate();
                filterCommand = {
                    id: newFilterCommandId,
                    code: 'rootviewmodelFilter1',
                    name: '过滤并加载数据1',
                    params: [
                        {
                            name: 'filter',
                            shownName: '过滤条件',
                            value: '{UISTATE~/root-component/originalFilterConditionList}'
                        },
                        {
                            name: 'sort',
                            shownName: '排序条件',
                            value: ''
                        }
                    ],
                    handlerName: 'Filter',
                    cmpId: this.loadCommandCmpId,
                    shortcut: {},
                    extensions: []
                };
                viewModel.commands.push(filterCommand);
            }

            const filterCommandCode = filterCommand.code;
            querySchemeMetadata.onQuery = filterCommandCode;
        }

        // 6、预置筛选方案查询数据的构件
        if (this.domService.module.webcmds) {
            let loadDataCmd = this.domService.module.webcmds.find(cmd => cmd.id === this.loadCommandCmpId);
            if (!loadDataCmd) {
                loadDataCmd = {
                    id: this.loadCommandCmpId,
                    path: 'igix/Web/WebCmp/bo-webcmp/metadata/webcmd/data-commands',
                    name: 'LoadCommands.webcmd',
                    refedHandlers: []
                };
                this.domService.module.webcmds.push(loadDataCmd);
            }
            if (newFilterCommandId) {
                loadDataCmd.refedHandlers.push(
                    {
                        host: newFilterCommandId,
                        handler: 'Filter'
                    }
                );

            }
        }

        // 因为涉及到新增【LoadCommands控制器】，所以这里需要获取控制器信息，方便交互面板展示命令数据
        this.webCmdService.checkCommands();
    }

    /**
     * 移除筛选方案
     */
    removeQuerySchemeInDocument() {
        if (!this.querySchemeConfig) {
            return;
        }

        // 1、移除指定位置的筛选(默认为根组件)
        const rootComponentJson = this.domService.getComponentById('root-component');
        const listFilterContainerParent = this.domService.getNodeByIdPath(rootComponentJson, this.querySchemeConfig.position);
        const querySectionIndex = listFilterContainerParent.contents.findIndex(c => c.type === DgControl.Section.type &&
            c.appearance && c.appearance.class && c.appearance.class.includes('f-section-scheme'));
        if (querySectionIndex < 0) {
            // console.log('未检测到筛选方案容器');
            return;
        }
        const querySection = listFilterContainerParent.contents[querySectionIndex];
        if (!querySection.contents || querySection.contents.findIndex(c => c.type === DgControl.QueryScheme.type) < 0) {
            // console.log('未检测到筛选方案控件');
            return;
        }
        listFilterContainerParent.contents.splice(querySectionIndex, 1);


        // 2、关联DOM处理--目前只处理样式
        if (this.querySchemeConfig.relatedClass && this.querySchemeConfig.relatedClass.length) {
            this.querySchemeConfig.relatedClass.forEach(r => {
                const relateDom = this.domService.getNodeByIdPath(rootComponentJson, r.path);
                if (relateDom) {
                    if (relateDom.appearance && relateDom.appearance.class) {
                        relateDom.appearance.class = relateDom.appearance.class.replace(r.class, '');
                    }
                }

            });
        }
        // 3、移除筛选方案相关的变量
        const viewModel = this.domService.getViewModelById(rootComponentJson.viewModel);
        if (viewModel && viewModel.states) {
            const filterVariableIndex = viewModel.states.findIndex(state => state.code === 'originalFilterConditionList');
            if (filterVariableIndex > -1) {
                viewModel.states.splice(filterVariableIndex, 1);
            }
        }
    }
}
